<script setup lang="ts">
import { service } from '@/apis/index';
import router from '@/router/index';
import { useStore } from '@/store/index';
import { Snackbar } from '@varlet/ui';
import { onUnmounted, reactive, ref, watch } from 'vue';
import PicCaptcha from './pic-captcha.vue';

const { user } = useStore()

const form = reactive({
  realName: '',
  mobile: '',
  email: '',
  emailId: '',
  emailCode: '',
  password: '',
  confirmPassword: '',
  agree: true,
  captchaId: '',
  verifyCode: ''
})

const isViewPassword = ref(false)
const isViewConfirmPassword = ref(false)

const pic = ref()
const saving = ref(false)

// 发送邮箱验证码
const isSendingCode = ref(false)
const countdown = ref(60)
const isEmailValid = ref(false)
let timer: ReturnType<typeof setInterval>

let debounceTimer: ReturnType<typeof setTimeout>
function sendEmailCode() {
  if (isSendingCode.value || !isEmailValid.value) return
  isSendingCode.value = true

  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => {
    service({
      path: '/student/index/sendEmailCode',
      method: 'post',
      data: { email: form.email }
    })
      .then((r) => {
        form.emailId = r.emailId
        Snackbar.success('验证码发送成功，请前往邮箱查看')
        startCountdown()
      })
      .catch((err) => {
        isSendingCode.value = false
        Snackbar.error(err.message)
      })
  }, 300) // 延迟 300 毫秒
}

function startCountdown() {
  countdown.value = 60
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
      isSendingCode.value = false
    }
  }, 1000)
}

onUnmounted(() => {
  clearInterval(timer) // 清理计时器
})

// 邮箱验证
watch(
  () => form.email,
  (newVal) => {
    isEmailValid.value = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(newVal)
  }
)

async function submit() {
  if (!form.realName) {
    return Snackbar.error('真实姓名不能为空')
  }
  if (!form.mobile) {
    return Snackbar.error('手机号不能为空')
  }
  if (!form.email) {
    return Snackbar.error('邮箱不能为空')
  }
  if (!form.emailCode) {
    return Snackbar.error('邮箱验证码不能为空')
  }
  if (!form.password) {
    return Snackbar.error('密码不能为空')
  }
  if (form.password !== form.confirmPassword) {
    return Snackbar.error('两次密码输入不一致')
  }
  if (!form.verifyCode) {
    return Snackbar.error('图片验证码不能为空')
  }
  if (!form.captchaId) {
    return Snackbar.error('请发送验证码')
  }
  // if (!form.agree) {
  //   return Snackbar.error("请同意注册协议");
  // }

  saving.value = true

  try {
    const ret = await service({ path: '/student/index/register', method: 'post', data: form })
    // 自动登录 
    user.setToken(ret)
    user.getInfo()
    Snackbar.success('注册成功')
    // router.push('/')
    router.push('/layout/home')
  } catch (err) {
    pic.value.refresh()
    Snackbar.error(err.message)
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <router-stack>
    <div class="sign-up">
      <app-header title="注册">
        <template #left>
          <app-back />
        </template>
      </app-header>

      <var-form class="sign-up-form">
        <var-space direction="column" :size="['4vmin', 0]">
          <var-input variant="outlined" placeholder="请输入真实姓名" v-model="form.realName"
            :rules="[(v) => !v || /^[\u4e00-\u9fa5]{1,6}$/.test(v) || '请输入1到6个汉字']">
            <template #prepend-icon>
              <var-icon class="sign-up-form-input-icon" name="account-circle" />
            </template>
          </var-input>
          <var-input variant="outlined" placeholder="请输入手机号" v-model="form.mobile"
            :rules="[(v) => !v || /^1[3-9]\d{9}$/.test(v) || '手机号格式不正确']">
            <template #prepend-icon>
              <var-icon class="sign-up-form-input-icon" name="phone" />
            </template>
          </var-input>
          <var-input variant="outlined" placeholder="请输入邮箱" v-model="form.email">
            <template #prepend-icon>
              <var-icon class="sign-up-form-input-icon" name="email" />
            </template>
          </var-input>
          <var-input variant="outlined" placeholder="请输入邮箱验证码" v-model="form.emailCode">
            <template #prepend-icon>
              <var-icon class="sign-up-form-input-icon" name="email-outline" />
            </template>
            <template #append-icon>
              <var-button type="primary" @click="sendEmailCode" :disabled="!isEmailValid || isSendingCode">
                {{ isSendingCode ? `${countdown}s 后重试` : '发送验证码' }}
              </var-button>
            </template>
          </var-input>
          <var-input variant="outlined" placeholder="请输入密码" :type="isViewPassword ? 'text' : 'password'"
            v-model="form.password">
            <template #append-icon>
              <var-icon class="sign-up-form-input-icon" :name="isViewPassword ? 'view' : 'view-outline'"
                @click="isViewPassword = !isViewPassword" />
            </template>
          </var-input>
          <var-input variant="outlined" placeholder="请确认密码" :type="isViewConfirmPassword ? 'text' : 'password'"
            v-model="form.confirmPassword">
            <template #append-icon>
              <var-icon class="sign-up-form-input-icon" :name="isViewConfirmPassword ? 'view' : 'view-outline'"
                @click="isViewConfirmPassword = !isViewConfirmPassword" />
            </template>
          </var-input>
          <var-input variant="outlined" placeholder="请输入图片验证码" v-model="form.verifyCode">
            <template #append-icon>
              <pic-captcha ref="pic" v-model.trim="form.captchaId" @change="() => (form.verifyCode = '')"
                style="width: 100px; height: 40px" />
            </template>
          </var-input>
          <!-- <var-checkbox v-model="form.agree">我同意 <a href="#">注册协议</a></var-checkbox> -->
          <var-button type="primary" block size="large" auto-loading @click="submit">注册</var-button>
        </var-space>
      </var-form>
    </div>
  </router-stack>
</template>

<style lang="less" scoped>
.sign-up {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: calc(var(--app-bar-height)) 0 60px;

  &-form {
    // width: 300px;
    width: 90%;
    margin-top: 30px;

    &-input-icon {
      margin-right: 10px;
      font-size: 24px;
    }
  }
}
</style>
